package com.kun.index.controller;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.Constants;
import com.kun.common.ResultDto;
import com.kun.common.annotation.PermissionAuthentication;
import com.kun.common.exception.MyException;
import com.kun.index.entity.Blog;
import com.kun.index.service.impl.AttachServiceImpl;
import com.kun.index.service.impl.BlogServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author kunkun
 * @since 2024-02-29
 */
@RestController
@RequestMapping("/index/attach")
public class AttachController {

    @Autowired
    private AttachServiceImpl attachService;

    @Value("${file.download.sqlFileName}")
    private String sqlFileName;            //备份文件名称




    @Value("${file.upload.pictureFilePrefix}")
    private String pictureFilePrefix;           //博客图片的下载路径前缀

    @Value("${file.download.sqlFilePath}")
    private String sqlFilePath;           //数据库文件的下载路径路径

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public ResultDto uploadAttach(@RequestParam("file") MultipartFile file){

        String url = attachService.uploadAttach(file);

        return ResultDto.success(pictureFilePrefix +url);

    }

    @PostMapping("/uploadTyporaPlugin")
    @ApiOperation("上传文件-Typora插件")
    @PermissionAuthentication
    public String uploadTyporaPlugin(@RequestParam("file") MultipartFile file){

        String url = attachService.uploadAttach(file);

        return pictureFilePrefix +url;

    }


    @GetMapping("/download/sqlFile")
    @ApiOperation("下载数据库sql文件")
    @PermissionAuthentication
    public ResultDto downloadSqlFile(HttpServletResponse response) throws IOException {

        //        1. 通过response获得outputStream
        ServletOutputStream outputStream = response.getOutputStream();

//        2. 通过outputStream设置响应头和类型
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(sqlFileName+".sql","UTF-8"));
        response.setContentType("application/octet-stream");

//        3. 通过flush方法进行下载
        File file = new File(sqlFilePath + sqlFileName + ".sql");
        outputStream.write(FileUtil.readBytes(file));
        outputStream.flush();
        outputStream.close();
        return ResultDto.success("下载成功");

    }

    @GetMapping("/getSqlFileLastUpdateTime")
    @ApiOperation("获取文件的最新备份时间")
    public ResultDto getSqlFileLastUpdateTime()  {

        String filePath=sqlFilePath + sqlFileName + ".sql";
        try{
            BasicFileAttributes attrs = Files.readAttributes(Paths.get(filePath), BasicFileAttributes.class);
            long lastModifiedTime = attrs.lastModifiedTime().toMillis();
            return ResultDto.success(lastModifiedTime);
        }catch (Exception e){
            throw  new MyException(Constants.CODE_301,"还未进行备份");
        }


    }

}

